package cn.jly.flink.source2sink.datastream.source;

import cn.jly.flink.entity.SensorReading;
import cn.jly.flink.utils.FlinkUtils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @PackageName cn.jly.flink.source2sink.datastream.source
 * @ClassName FileSource
 * @Description fileSource
 * @Author 姬岚洋
 * @Date 2021/1/26 下午 4:28
 */
public class FileSource {
    public static void main(String[] args) throws Exception {
        final StreamExecutionEnvironment env = FlinkUtils.getStreamExecutionEnv();
        // 设置全局并行度
        env.setParallelism(1);

        env.readTextFile("d:/SensorReading.txt")
                .flatMap(new FlatMapFunction<String, SensorReading>() {
                    @Override
                    public void flatMap(String value, Collector<SensorReading> out) throws Exception {
                        if (StringUtils.isNotEmpty(value)) {
                            try {
                                out.collect(JSON.parseObject(value, SensorReading.class));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                })
                .keyBy(new KeySelector<SensorReading, String>() {
                    @Override
                    public String getKey(SensorReading value) throws Exception {
                        return value.getId();
                    }
                })
                .print(Thread.currentThread().getName());


        FlinkUtils.executeStream(env, "FileSource");
    }


}
